package Orm.mybatis.exa03_pagePlugins;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.Properties;

@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class MyPageInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = invocation.getArgs()[1];
        RowBounds rowBounds = (RowBounds) invocation.getArgs()[2];

        // 判断是否是分页查询方法
        if (rowBounds != RowBounds.DEFAULT) {
            BoundSql boundSql = mappedStatement.getBoundSql(parameter);

            // 获取分页参数
            int offset = rowBounds.getOffset();
            int limit = rowBounds.getLimit();

            // 构建分页sql
            String newSql = boundSql.getSql() + " LIMIT " + offset + "," + limit;

            // 使原来的rowBounds失效,改用物理分页
            if (rowBounds.getOffset() != RowBounds.NO_ROW_OFFSET || rowBounds.getLimit() != RowBounds.NO_ROW_LIMIT) {
                MetaObject metaObject = SystemMetaObject.forObject(rowBounds);
                metaObject.setValue("offset", RowBounds.NO_ROW_OFFSET);
                metaObject.setValue("limit", RowBounds.NO_ROW_LIMIT);
            }

            // 重写BoundSql，将分页sql设置到其中
            BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), newSql, boundSql.getParameterMappings(), boundSql.getParameterObject());


            // 重写MappedStatement，将新BoundSql设置到其中
            MappedStatement newMappedStatement = newMappedStatement(mappedStatement, newBoundSql);

            // 调用新的MappedStatement进行查询
            invocation.getArgs()[0] = newMappedStatement;
        }

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return  Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }

    private MappedStatement newMappedStatement(MappedStatement ms, BoundSql boundSql) {

        MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(),o-> boundSql, ms.getSqlCommandType());
        builder.resultMaps(ms.getResultMaps())
                .cache(ms.getCache())
                .fetchSize(ms.getFetchSize())
                .flushCacheRequired(ms.isFlushCacheRequired())
                .keyColumn(join(ms.getKeyColumns()))
                .keyGenerator(ms.getKeyGenerator())
                .keyProperty(join(ms.getKeyProperties()))
                .lang(ms.getLang())
                .resource(ms.getResource());

        return builder.build();
    }

    private static String join(String[] strings) {
        StringBuilder stringBuilder = new StringBuilder();
        if(strings==null||strings.length==0) return null;
        if(strings.length==1) return strings[0];
        stringBuilder.append(strings[0]);
        for(int i=1;i<strings.length;i++){
            stringBuilder.append(",").append(strings[i]);
        }
        return stringBuilder.toString();
    }

}
